package com.hula.onion.book.server.dao.impl;

import com.hula.onion.book.server.dao.IRefundDao;
import com.hula.onion.book.server.model.RefundDetailInfo;
import com.hula.onion.book.server.model.RefundInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created by work on 2018/3/26.
 */

@Repository
public class RefundDaoImpl extends JdbcDaoSupport implements IRefundDao {

    @Resource(name = "dataSource")
    private DataSource dataSource;

    RefundDaoImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }


    private static final BeanPropertyRowMapper<RefundInfo> refundMapper =
            new BeanPropertyRowMapper<>(RefundInfo.class);

    private static final BeanPropertyRowMapper<RefundDetailInfo> refundDetailMapper =
            new BeanPropertyRowMapper<>(RefundDetailInfo.class);

    private static final String GET_REFUND_LIST = "select pri.id,pri.platform_id," +
            "pri.bank_management,pri.interest_rate,pri.refund_amount,pi.icon_url," +
            "pi.name from platform_refund_info pri left join" +
            " platform_info pi on pri.platform_id=pi.id limit ?,?;";

    @Override
    public List<RefundInfo> getRefundList(int page, int size) {
        int from = page * size;
        List<RefundInfo> refundInfos = this.getJdbcTemplate().query(GET_REFUND_LIST,
                new Object[]{from, size}, refundMapper);
        if (CollectionUtils.isEmpty(refundInfos)) {
            return Collections.emptyList();
        }
        return refundInfos;
    }


    private static final String GET_REFUND_DETAIL_LIST = "select pri.platform_desc,pri.platform_id," +
            "pri.special_info,pri.register_url,pri.refund_rule,pri.refund_amount," +
            "pi.icon_url,pi.name from platform_refund_info pri left join" +
            " platform_info pi on pri.platform_id=pi.id where pri.id=?;";

    @Override
    public RefundDetailInfo getRefundDetail(int id) {
        List<RefundDetailInfo> result = this.getJdbcTemplate().query(GET_REFUND_DETAIL_LIST,
                new Object[]{id}, refundDetailMapper);
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        return result.get(0);
    }
}
